package com.longe.security;

import com.longe.util.RedisUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.util.SerializationUtils;

import java.io.Serializable;

/**
 * 为了演示更加清晰，我们不使用RedisSession中的redisManager属性来操作redis
 */
public class MyRedisSessionDAO extends RedisSessionDAO{

    private String keyPrefix = "myProject:shiro:session:%s";

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);

        String key = String.format(keyPrefix, session.getId());
        byte[] value = SerializationUtils.serialize(session);
        RedisUtil.put(key.getBytes(), value, 30 * 60);

        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        if(null == sessionId){
           return null;
        }
        String key = String.format(keyPrefix, sessionId.toString());
        byte[] value = RedisUtil.get(key.getBytes());
        Object session = SerializationUtils.deserialize(value);

        return (Session) session;
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        if(null != session && null != session.getId()){
            String key = String.format(keyPrefix, session.getId());
            byte[] value = SerializationUtils.serialize(session);
            RedisUtil.put(key.getBytes(), value, 30 * 60);
        }
    }

    @Override
    public void delete(Session session) {
        if(null != session && null != session.getId()){
            String key = String.format(keyPrefix, session.getId());
            RedisUtil.del(key.getBytes());
        }
    }
}
